<template>
  <div class="map-container">
    <div id="map" class="map"></div>
  </div>
</template>

<script>
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import TileLayer from 'ol/layer/Tile'
import WMTS from 'ol/source/WMTS'
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import VectorLayer from 'ol/layer/Vector'
import VectorSource from 'ol/source/Vector'
import GeoJSON from 'ol/format/GeoJSON'
import { Style, Stroke, Fill } from 'ol/style'
import { fromLonLat, get as getProjection } from 'ol/proj'
import { getWidth, getTopLeft } from 'ol/extent'

export default {
  name: 'MaskDemo',
  data() {
    return {
      map: null,
      boundaryLayer: null,
      key: '8c88eba266a165eac9c085724708f2f9'  // 请替换为你的天地图密钥
    }
  },
  mounted() {
    this.initMap()
    this.loadBoundaryData()
  },
  methods: {
    initMap() {
      // 设置投影
      const projection = getProjection('EPSG:3857')
      const projectionExtent = projection.getExtent()
      const size = getWidth(projectionExtent) / 256
      const resolutions = new Array(18)
      const matrixIds = new Array(18)
      for (let z = 0; z < 18; ++z) {
        resolutions[z] = size / Math.pow(2, z)
        matrixIds[z] = z
      }

      // 初始化地图
      this.map = new Map({
        target: 'map',
        layers: [
          // 天地图影像作为底图
          new TileLayer({
            source: new WMTS({
              url: 'https://t0.tianditu.gov.cn/img_w/wmts?tk=' + this.key,
              layer: 'img',
              format: 'tiles',
              matrixSet: 'w',
              projection: projection,
              tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds
              }),
              style: 'default',
              wrapX: true
            })
          }),
          // 天地图影像注记
          new TileLayer({
            source: new WMTS({
              url: 'https://t0.tianditu.gov.cn/cia_w/wmts?tk=' + this.key,
              layer: 'cia',
              format: 'tiles',
              matrixSet: 'w',
              projection: projection,
              tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: matrixIds
              }),
              style: 'default',
              wrapX: true
            })
          })
        ],
        view: new View({
          center: fromLonLat([87.617733, 43.792818]), // 乌鲁木齐市中心坐标
          zoom: 6,
          minZoom: 5,
          maxZoom: 12
        })
      })
    },

    async loadBoundaryData() {
      try {
        const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/650000.json')
        const geoData = await response.json()
        console.log('原始GeoJSON数据:', geoData)

        // 创建遮罩数据
        const coordinates = geoData.features[0].geometry.coordinates[0]
        console.log('边界坐标:', coordinates)
        
        // 创建世界范围矩形（使用较大范围确保覆盖）
        const worldBounds = [
          [-180, -85], // 左下角
          [180, 85]    // 右上角
        ]
        
        // 将新疆边界作为内部孔洞
        const boundaryGeoJson = {
          type: 'FeatureCollection',
          features: [{
            type: 'Feature',
            geometry: {
              type: 'Polygon',
              coordinates: [
                // 外部矩形（世界范围）
                [
                  [worldBounds[0][0], worldBounds[1][1]], // 左上
                  [worldBounds[1][0], worldBounds[1][1]], // 右上
                  [worldBounds[1][0], worldBounds[0][1]], // 右下
                  [worldBounds[0][0], worldBounds[0][1]], // 左下
                  [worldBounds[0][0], worldBounds[1][1]]  // 回到左上，闭合多边形
                ],
                // 内部孔洞（新疆边界）
                coordinates[0]
              ]
            }
          }]
        }
        console.log('构建的GeoJSON:', boundaryGeoJson)
        
        // 创建矢量数据源
        const vectorSource = new VectorSource({
          features: new GeoJSON().readFeatures(boundaryGeoJson, {
            dataProjection: 'EPSG:4326', // 输入数据的坐标系统
            featureProjection: 'EPSG:3857'  // 输出/目标坐标系统
          })
        })
        console.log('矢量数据源:', vectorSource)
        console.log('要素列表:', vectorSource.getFeatures())
        console.log('地图投影:', this.map.getView().getProjection().getCode())

        // 创建矢量图层
        this.boundaryLayer = new VectorLayer({
          source: vectorSource,
          style: new Style({
            stroke: new Stroke({
              color: '#f56c6c',
              width: 2
            }),
            fill: new Fill({
              color: 'rgba(25, 118, 210, 0.3)'
            })
          })
        })

        // 添加图层到地图
        this.map.addLayer(this.boundaryLayer)

        // 缩放到数据范围
        // this.map.getView().setCenter(fromLonLat([87.617733, 43.792818]))
        // this.map.getView().setZoom(6)
      } catch (error) {
        console.error('加载边界数据失败:', error)
      }
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.setTarget(null)
      this.map = null
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}
</style> 